package org.example;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * Author:qqw
 * Date:2024-06-18
 * Description:请求接受处理器
 */
@Slf4j
public class ReceiveServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext receiveCtx, Object msg) throws Exception {
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.group(receiveCtx.channel().eventLoop())
                .channel(NioSocketChannel.class)
                .handler(new ForwarderServerHandler(receiveCtx,msg));
        ServiceHostPortEnum byService = ServiceHostPortEnum.getByService(ServiceSelector.getService(msg));
        Integer port = byService.getPort();
        try {
            clientBootstrap.connect(byService.getIp(),port).addListener((ChannelFutureListener) future1 -> {
                if (future1.isSuccess()) {
                    log.info("NettyDis 连接成功! port:{}",port);
                } else {
                    log.info("NettyDis 连接失败! port:{}",port);
                }
            });;
        }catch (Throwable e){
            e.printStackTrace();
            log.error("exception on handling msg {} , cause:{}",DecodeUtil.decode((ByteBuf) msg),e.getMessage());
            throw e;
        }
        log.info("NettyDispatcher 连接 {} 端口成功", port);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
